'use strict'

process.chdir(__dirname)

const titbit = require('titbit')
const fs = require('fs')
const dbcfg = require('./dbconfig.js')
const pg = require('pg')
const wxkey = require('./wxkey.js')
const { httpcli } = require('gohttp')
const token = require('titbit-token')
const tbloader = require('titbit-loader')
const { parsebody } = require('titbit-toolkit')
const { userInfo } = require('os')

try {
    fs.accessSync('./images')
} catch (err) {
    fs.mkdirSync('./images')
}

let psql = new pg.Pool(dbcfg)

//证书文件所在目录
let cert_path = '/home/ubuntu/www.h5fd.xyz'

const app = new titbit({
    //开启调试模式，若有错误会输出错误信息。
    debug: true,
    globalLog: true,
    //证书文件路径
    cert: `${cert_path}/www.h5fd.xyz.pem`,
    key: `${cert_path}/www.h5fd.xyz.key`
})

if (process.argv.indexOf('--local') > 0) {
    app.config.https = false;
    app.config.cert = app.config.key = '';
}

let tb = new tbloader();
tb.init(app);

app.addService('psql', psql);

app.addService('imagePath', `${__dirname}/images`);

let tok = new token({
    //token有效期，单位为秒
    expires: 7200,
    //必须是32位字符
    key: '1qaz2wsx3edc4rfv5tgb6yhn7ujmki89',

    //必须是16位字符
    iv: '1q2w3e4r5t6y7u8i'
})

//用于管理员会话验证
app.addService('tok', tok)

//用于用户端的会话验证
let usertok = new token({
    //token有效期，单位为秒
    expires: 7200,
    //必须是32位字符
    key: '1qaz2wsx3edc4rfv5tgb6yhn7ujm0967',

    //必须是16位字符
    iv: '112w3e4r5t667u78'
})

app.addService('usertok', usertok)

async function checkAndInsert(psql, u) {
    let sql = 'SELECT openid FROM openid WHERE openid = $1'
    let r = await psql.query(sql, [u.openid])
    if (r.rowCount > 0) return true;
    r = await psql.query('INSERT INTO openid(openid) VALUES($1)', [u.openid])
    return r.rowCount > 0 ? true : false;
}

//小程序端调用wx.login进行登录验证，需要发送code到此请求。

app.get('/mp-login/:code', async c => {
    try {
        let auth_url = `https://api.weixin.qq.com/sns/jscode2session`
            + `?appid=${wxkey.appid}`
            + `&secret=${wxkey.secret}`
            + `&js_code=${c.param.code}`
            + `&grant_type=authorization_code`

        let ret = await httpcli.get(auth_url)
            .then(async res => {
                res = res.json();
                return res
            });
        if (!ret.openid) {
            return c.status(500).send('登录失败。');
        }

        //检测并写入到数据库 openid
        await checkAndInsert(c.service.psql, ret);
        return c.send(usertok.make(ret));

    } catch (err) {
        console.log(err);
        return c.status(500).send('other error');
    }
});


app.post('/adminlogin', async c => {
    try {
        var loginObj = JSON.parse(c.body);
        var sqltext = `select * from admin where admin_name = '${loginObj.username}'`
        let r = await psql.query(sqltext)
        if (r.rowCount > 0) {
            if(r.rows[0].admin_passwd==loginObj.passwd){
                var newtok = tok.make(loginObj);
                return c.send(newtok);
            }
            else{
                return ('登陆失败')
            }
        }
        else {
            return c.send('登陆失败')
        }
    } catch (err) {
        console.log(err)
    }
})
app.use(new parsebody);


//运行在2021端口
app.run(2021);
